package com.hmall.search.service;

import com.alibaba.fastjson.JSON;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.pojo.Item;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.ItemDto;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchSevice {
    RestHighLevelClient client;

    private SearchSevice() {
        client = new RestHighLevelClient(RestClient
                .builder(HttpHost.create("192.168.119.128:9200")));
    }

    public Map<String, List<String>> filters(ItemDto itemDto) throws IOException {

        SearchRequest request = new SearchRequest("item");
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //筛选
        base(itemDto, request, boolQueryBuilder);


        //聚合搜索
        request.source().aggregation(AggregationBuilders.terms("categoryAgg")
                .field("category")
                .size(20));
        request.source().aggregation(AggregationBuilders.terms("brandAgg")
                .field("brand")
                .size(30));
        Map<String, List<String>> map = new HashMap<>();

        //发送
        request.source().query(boolQueryBuilder);

        SearchResponse search = client.search(request, RequestOptions.DEFAULT);

        //分析
        Aggregations aggregations = search.getAggregations();

        get(map,aggregations,"categoryAgg","category");
        get(map,aggregations,"brandAgg","brand");
        return map;

    }

    private void get(Map<String, List<String>> map, Aggregations aggregations,String name,String mao){
        Terms terms =aggregations.get(name);
        List<String> list = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            String keyAsNumber = bucket.getKeyAsString();
            list.add(keyAsNumber);
        }
        map.put(mao,list);
    }

    /**
     * 模糊搜索
     * @param itemDto
     * @param request
     * @param boolQueryBuilder
     */
    private void base(ItemDto itemDto, SearchRequest request, BoolQueryBuilder boolQueryBuilder) {
        if (StringUtils.isNotBlank(itemDto.getKey())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", itemDto.getKey()));
        }
        if (StringUtils.isNotBlank(itemDto.getCategory())) {
            boolQueryBuilder.must(QueryBuilders.termQuery("category", itemDto.getCategory()));

        }
        if (StringUtils.isNotBlank(itemDto.getBrand())) {
            boolQueryBuilder.must(QueryBuilders.termQuery("brand", itemDto.getBrand()));

        }
        if (itemDto.getMaxPrice() != null && itemDto.getMinPrice() != null) {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("price")
                    .gte(itemDto.getMinPrice()*100)
                    .lte(itemDto.getMaxPrice()*100));
        }

        //排序
        if ("default".equals(itemDto.getSortBy())) {

        }else if ("sold".equals(itemDto.getSortBy())){
            request.source().sort("sold",SortOrder.ASC);

        }
        //分页
        request.source().from((itemDto.getPage() - 1) * itemDto.getSize()).size(itemDto.getSize());
    }

    public PageDTO<ItemDoc> list(ItemDto itemDto) throws IOException {

        SearchRequest request = new SearchRequest("item");
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //模糊搜索
        base(itemDto, request, boolQueryBuilder);
        //发送
        request.source().query(boolQueryBuilder);

        //高亮
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));


        SearchResponse search = client.search(request, RequestOptions.DEFAULT);
        SearchHit[] hits = search.getHits().getHits();
        PageDTO<ItemDoc> itemDocPageDTO = new PageDTO<>();
        ArrayList<ItemDoc> itemDocs = new ArrayList<>();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();

            ItemDoc itemDoc = JSON.parseObject(sourceAsString, ItemDoc.class);
            Map<String, HighlightField> ma = hit.getHighlightFields();
            if (ma.size()>0){
                String name = ma.get("name").getFragments()[0].toString();
                itemDoc.setName(name);
            }
            itemDocs.add(itemDoc);

        }
        itemDocPageDTO.setList(itemDocs);
        itemDocPageDTO.setTotal(search.getHits().getTotalHits().value);
        return itemDocPageDTO;

    }


    /**
     * 自动补全
     *
     * @param key
     * @return
     * @throws IOException
     */
    public List<String> get(String key) throws IOException {

        SearchRequest request = new SearchRequest("item");
        request.source().suggest(new SuggestBuilder().addSuggestion(
                "suggestions",
                SuggestBuilders.completionSuggestion("suggestion")
                        .prefix(key)
                        .skipDuplicates(true)
                        .size(10)
        ));
        SearchResponse search = client.search(request, RequestOptions.DEFAULT);
        Suggest suggest = search.getSuggest();
        CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
        List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
        ArrayList<String> list = new ArrayList<>();
        for (CompletionSuggestion.Entry.Option option : options) {
            String s = option.getText().toString();
            list.add(s);
        }


        return list;
    }
}
